package api

import (
	"alarm_service/common/client_conn"
	"alarm_service/internal/usecase/tcp"
	"net"
)

type TcpApi struct {
	heartBeatCase  *tcp.HeartBeatCase
	deviceInfoCase *tcp.DeviceInfoCase
	callBackCase   *tcp.CallBackCase
}

func NewTcpApi(hc *tcp.HeartBeatCase, dc *tcp.DeviceInfoCase, cc *tcp.CallBackCase) *TcpApi {
	return &TcpApi{
		heartBeatCase:  hc,
		deviceInfoCase: dc,
		callBackCase:   cc,
	}
}

func (a *TcpApi) OnPhoneCallBackHandler(packet []byte, conn net.Conn) {
	err := a.callBackCase.SetPhoneCallBack(packet, conn)
	if err != nil {
		conn.Write([]byte("SIA01E"))
	} else {
		conn.Write([]byte("SIA00E"))
	}
}

func (a *TcpApi) OnMsgSwitchCallBackHandler(packet []byte, conn net.Conn) {
	err := a.callBackCase.SetMessageSwitchCallBack(packet, conn)
	if err != nil {
		conn.Write([]byte("SIB00E"))
	} else {
		conn.Write([]byte("SIB00E"))
	}
}

func (a *TcpApi) OnResetCallBackHandler(packet []byte, conn net.Conn) {
	err := a.callBackCase.SetRecoverCallBack(packet, conn)
	if err != nil {
		conn.Write([]byte("SIC00E"))
	} else {
		conn.Write([]byte("SIC00E"))
	}
}

func (a *TcpApi) OnPhoneSwitchCallBackHandler(packet []byte, conn net.Conn) {
	err := a.callBackCase.SetPhoneSwitchCallBack(packet, conn)
	if err != nil {
		conn.Write([]byte("SIF00E"))
	} else {
		conn.Write([]byte("SIF00E"))
	}
}

func (a *TcpApi) OnHeartBeatHandler(packet []byte, conn net.Conn) {
	err := a.heartBeatCase.HeartBeat(packet, conn)
	if err != nil {
		conn.Write([]byte("SIH01E"))
	} else {
		conn.Write([]byte("SIH00E"))
	}
}

func (a *TcpApi) OnInfoHandler(packet []byte, conn net.Conn) {
	err := a.deviceInfoCase.Analysis(packet, conn)
	if err != nil {
		conn.Write([]byte("SIG01E"))
	} else {
		conn.Write([]byte("SIG00E"))
	}
}

func (a *TcpApi) OnTcpCloseHandler(conn net.Conn) {
	deviceID := client_conn.Get(conn)
	if deviceID != 0 {
		a.deviceInfoCase.DeviceOffline(deviceID)
	}
}
